<template>
    <el-dialog
        :title = "'添加' + title"
        :visible.sync = "addDialogVisible"
        width = "50%"
        @close = "addClosed">
        <el-form ref = "addFormRef" :model = "addForm" :rules = "addFormRules">
            <el-form-item :label = "title" prop = "attr_name">
                <el-input v-model = "addForm.attr_name" :placeholder = "title"
                          @keyup.enter.native = "add"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot = "footer" class = "dialog-footer">
            <el-button @click = "addDialogVisible = false">取 消</el-button>
            <el-button type = "primary" @click = "add" @keyup.enter.native = "add">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script type = "text/javascript">
export default {
    name: "MyAdd",
    props: ['activeName', "cateId", "row"],
    data () {
        return {
            addForm: {
                attr_name: ""
            },
            addFormRules: {
                attr_name: [
                    {required: true, message: "请输入参数名称", trigger: 'blur'}
                ]
            },
            addDialogVisible: false,
        }
    },
    computed: {
        // 动态计算标题文本
        title () {
            if (this.activeName === "many") {
                return "动态参数";
            }
            return "静态属性";
        },
    },
    methods: {
        // 监听对话框关闭事件
        addClosed () {
            this.$refs.addFormRef.resetFields();
        },
        // 添加请求事件
        add () {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return;
                const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.addForm.attr_name,
                    attr_sel: this.activeName
                });
                if (res.meta.status !== 201) {
                    return this.$message.error("添加参数失败");
                }
                this.$message.success("添加参数成功");
                this.addDialogVisible = false;
                this.$emit("getParamsData");
            })
        }
    }
}
</script>

<style lang = "less" scoped>

</style>
